/**
 * Created by 长春驿枫 on 2015/6/13.
 *
 */

!(function(){
    var __functionForPlugin=function (Ladder) {
        Ladder.NS("MoreQuery");
        Ladder.MoreQuery=function(option){
            this.settings={
                height:300,
                parent:null,
                fieldUrl:null,
                fieldData:null,
                templateUrl:null,
                saveUrl:null,
                saveExter:null,
                relation:"all",
                single:false,
                id:"",
                store:"local",
                take:"json",
                onSave:null,
                onQuery:null,
                onReset:null,
            };
            this.Component=null;
            this.fieldEl=null;
            this.conditionEl=null;
            this.templateEl=null;
            this.fieldData={};
            this.swapEvent=null;
            this.holdData=null;//保持数据，用于保存上次查询的条件或者其他数据，

            if(option){
                $.extend(this.settings,option);
                if(!this.settings.id&&this.settings.store.indexOf("local")>-1){
                    this.settings.store.replace("local","");
                }
                return this.init(this.settings)
            }
        }
        Ladder.MoreQuery.prototype={
            init:function(option){
                var settings=option||this.settings;
                var me=this;
                me.Component=$("<div class='yui-morequery'></div>").appendTo(me.settings.parent?me.settings.parent:document.body);
                var $head=$("<div class='yui-morequery-head'></div>").appendTo(me.Component);
                $head.append('<div class="tpls"> <ul></ul></div>');
                var $abtns=$('<div class="abtns"></div>').appendTo($head);
                var layerid=null;
                //新增
                $('<i class="iconfont icon-add"></i><a href="##">新增</a>').appendTo($abtns).click(function(){
                    me.Component.find(".addInputOuter").show();
                    me.Component.find(".addInput").fadeIn(500);
                    $Container.find(".addInput input").val("");
                });
                $('<i class="iconfont icon-rename"></i><a href="##">改名</a>').appendTo($abtns).click(function(){
                    if(!me.conditionEl||me.conditionEl.length<1)return;
                    me.Component.find(".addInputOuter").show();
                    me.Component.find(".addInput").fadeIn(500);
                    $Container.find(".addInput input").val("");
                    me.swapEvent=function(title){
                        me.conditionEl.attr("data-oldtitle",me.conditionEl.attr("data-title")).attr("data-title",title);
                        me.Component.find(".tpls li.current").html(title).addClass("nosave");
                    };
                });
                //保存
                $('<i class="iconfont icon-save"></i><a href="##">保存</a>').appendTo($abtns).click(function(){
                    if(me.conditionEl.attr("data-title")=="未命名"){
                        me.Component.find(".addInputOuter").show();
                        me.Component.find(".addInput").fadeIn(500);
                        $Container.find(".js-addTemplate input").val("");
                        me.swapEvent=function(title){
                            me.conditionEl.attr("data-title",title);
                            me.Component.find(".tpls li.current").html(title);
                            me.saveTemplate();
                            layer.msg("保存操作已处理");
                        };
                    }else{
                        me.saveTemplate();
                        layer.msg("保存操作已处理");
                    }
                    //
                    //layer.confirm('请您确认是否全部保存', {
                    //    btn: ['保存当前', '取消保存'], //按钮
                    //    shade: false, //不显示遮罩
                    //    title:"是否删除当前模版"
                    //},function(id){
                    //    layer.close(id);
                    //
                    //});
                });
                //删除
                $('<i class="iconfont icon-delete"></i><a href="##">删除</a>').appendTo($abtns).click(function(){
                    layer.confirm('请您确认是否删除', {
                        btn: ['确认删除', '取消返回'], //按钮
                        shade: false, //不显示遮罩
                        title:"是否删除当前模版"
                    }, function (layerid) {
                        layer.close(layerid);
                        var currentTab = $head.find(".tpls li.current");
                        if(currentTab.length<1)return;
                        var index=currentTab.index();
                        var nextTab=currentTab.next();
                        if(nextTab.length<1)nextTab=currentTab.prev();
                        me.saveTemplate(null,true);
                        currentTab.remove();
                        me.templateEl.find(".queryform:eq("+index+")").remove();
                        if(nextTab.length<1){
                            me.Component.find(".js-querybtns").hide();
                        }else{
                            nextTab.trigger("click");
                            if(me.conditionEl.find(".queryitem").length<1)me.Component.find(".js-querybtns").hide();
                        }
                    });
                });
                var $main=$('<div class="yui-morequery-mainpanel">').appendTo(me.Component);
                var $leftNav=$('<div class="yui-morequery-fields"></div>').appendTo($main);
                var $search = $('<input type="text" class="search_input">').appendTo($leftNav);
                //搜索框输入时
                $search.keyup(function(){
                    var val=$(this).val();
                    if(val.length<1){
                        me.fieldEl.find(".fielditem").show(100);
                        return;
                    }
                    me.fieldEl.find(".fielditem").hide(100).each(function(){
                        var text=$(this).text();
                        if(text.indexOf(val)>-1)$(this).show();
                    });
                });
                me.fieldEl=$('<div class="columns"></div>').appendTo($leftNav).css("height",me.settings.height);
                //右侧的条件表单
                var $Container=$("<div style='float: left'></div>").appendTo($main);
                //添加新模版输入框
                var $addtemplate = $("<div class='addInput'>" +
                    "<span>请给模板命名</span>" +
                    "<input style='height: 23px;margin: 0 3px' class='js-newTemplateName'>" +
                    "<button class='submit'>确定</button>" +
                    "<button class='cancel' style='margin-left: 3px'>取消</button>" +
                    "</div>").appendTo(me.Component).hide();
                $("<div class='addInputOuter'></div>").appendTo(me.Component);
                //添加新模版提交按钮
                $addtemplate.find(".submit").click(function(){
                    var title = $(this).siblings("input").val();
                    var lis=me.Component.find("ul li");
                    for(var i= 0,len=lis.length;i<len;i++){
                        var text=$(lis[i]).text();
                        if(text==title){
                            layer.msg("模版名称重复,请重新命名",{icon:2});
                            return;
                        }
                    }
                    me.Component.find(".addInputOuter").hide();
                    me.Component.find(".addInput").fadeOut(500);
                    if(me.swapEvent){
                        me.swapEvent(title);
                        me.swapEvent=null;
                    }else {
                        var $newTab = me.addTab({title:title});
                        if($newTab)$newTab.addClass("nosave");
                    }
                });
                $addtemplate.find(".cancel").click(function(){
                    me.Component.find(".addInputOuter").hide();
                    me.Component.find(".addInput").fadeOut(500);
                });
                //添加新模版输入框回车
                $addtemplate.find("input").keyup(function(e){
                    if (e.keyCode == 13) $addtemplate.find(".submit").trigger("click");
                });
                //模版容器
                me.templateEl= $("<div class='templateTab'></div>").appendTo($Container).css({"height":me.settings.height,width:535});
                var btnArea = $("<div style='text-align: center;margin-top: 5px;' class='js-querybtns'></div>").appendTo($Container).hide();
                $("<button class='submit'>查询</button>").appendTo(btnArea).click(function(){
                    if(!Ladder.form.vaildForm(me.conditionEl))return;
                    if(me.settings.onQuery)me.settings.onQuery(me.fetchCondition());
                });
                $("<button class='cancel'>取消</button>").appendTo(btnArea).click(function(){
                    if(me.settings.onReset)me.settings.onReset();
                });
            },
            /***
             * 添加选项卡
             * @param data 数据,可以是数组和对象
             * @param isshow 是否当前显示  默认显示
             */
            addTab:function(data,isshow){
                var me=this;
                if(!data)return;
                if(isshow==undefined)isshow=true;
                data=Ladder.toJSON(data);
                var type=Ladder.getType(data);
                switch (type){
                    case "String":
                        data={title:data};
                        break;
                    case "Array":
                        data.forEach(function(item,index){
                            if(index>0)me.addTab(item,false);
                            else me.addTab(item);
                        });
                        return;
                }
                if(Ladder.getType(data)=="String")data={title:data};
                if(!data.id)data.id=Ladder.timecode(20);
                var $newTab=$("<li>"+data.title+"</li>").attr("data-id",data.id);
                me.Component.find("ul").append($newTab);
                me.Component.find("ul li").off().click(function() {
                    $(this).addClass("current").siblings().removeClass("current");
                    me.conditionEl=me.templateEl.find(".queryform:eq("+$(this).index()+")").show();
                    me.conditionEl.siblings().hide();
                    if(me.conditionEl.find(".queryitem").length<1)me.Component.find(".js-querybtns").hide();
                });
                var conditionEl=null;
                if(isshow){
                    $newTab.addClass("current").siblings().removeClass("current");
                    me.Component.find(".js-querybtns").hide();
                    me.templateEl.find(".queryform").hide();
                    me.conditionEl=$("<div class='queryform'></div>").appendTo(me.templateEl)
                        .attr("data-title",data.title).attr("data-id",data.id).attr("data-action",1);
                    conditionEl=me.conditionEl;
                }else{
                    conditionEl=$("<div class='queryform' data-title='"+data.title+"'></div>").appendTo(me.templateEl).hide()
                        .attr("data-title",data.title).attr("data-id",data.id).attr("data-action",1);
                }
                if(data.template){
                    conditionEl.attr("data-action",2);
                    data.template.forEach(function(item){
                        me.addCondition($.extend(me.fieldData[item["fieldname"]],item),conditionEl);
                    });
                }
                return $newTab;

            },
            addField:function(config){
                if(!config)return;
                var me=this;
                var type=Ladder.getType(config);
                switch (type){
                    case "Array":
                        config.forEach(function(item){
                            me.addField(item);
                        });
                        break;
                    case "Object":
                        if(config.fieldname){
                            var $fielditem=$('<div class="fielditem" data-fieldname="'+config.fieldname+'"><i class="iconfont icon-add"></i><a>'+config.title+'</a></div>');
                            me.fieldEl.append($fielditem);
                            $fielditem.click(function(){
                                me.addCondition(config);
                                me.Component.find(".tpls ul li.current").addClass("nosave");
                            });
                            me.fieldData[config.fieldname]=config;
                        }
                        break;
                    case "string":
                        var json=Ladder.toJSON(config);
                        if(Ladder.getType(json)=="Object")me.addField(json);
                        else {
                            var $fielditem=$('<div class="fielditem"><i class="iconfont icon-add"></i><a>'+config+'</a></div>');
                            me.fieldEl.append($fielditem);
                            $fielditem.click(function(){
                                me.addCondition({fieldname:config,title:config});
                                me.Component.find(".tpls ul li.current").addClass("nosave");
                            });
                            me.fieldData[config]={fieldname:config,title:config};
                        }
                }
            },
            addCondition:function(data,conditionEl){
                var me=this;
                if(conditionEl==undefined)conditionEl=me.conditionEl;
                if(conditionEl==null){
                    me.addTab({title:"未命名"});
                    conditionEl=me.conditionEl;
                }
                if(me.settings.single&&conditionEl.find(".queryitem[data-fieldname='"+data.fieldname+"']").length>0) return;
                var $condition = $('<div class="queryitem" data-fieldname="'+data.fieldname+'">');
                $('<i class="iconfont">&#xe72a;</i>').appendTo($condition).click(function () {
                    $condition.remove();
                    if(conditionEl.find(".queryitem").length<1)me.Component.find(".js-querybtns").hide();
                });
                $('<label>'+(data.title?(data.title.length>5?data.title.substr(0,4)+"…":data.title):"")+'</label>').appendTo($condition);
                if((data.type&&/date/.test(data.type))||data.wname=="datebox"){
                    data.wname="datebox";
                    me.createOp("between").appendTo($condition).prop("disabled",true);
                    Ladder.Form.createForm(data,data.val1).appendTo($condition).val(data.val1);
                    $("<span>至</span>").appendTo($condition);
                    me.createOp("<=").appendTo($condition).hide();
                    Ladder.Form.createForm(data,data.val2).appendTo($condition).val(data.val2);
                }else {
                    var $op = me.createOp(data.op||"=").appendTo($condition);
                    if(data.op)$op.hide();
                    Ladder.Form.createForm(data,data.val1).appendTo($condition).val(data.val1);
                }
                switch (me.settings.relation){
                    case "all":
                    case true:
                    case 2:
                        $('<select class="js-relation"><option value="and" selected>并且</option><option value="or">或者</option><select/>').appendTo($condition);
                        break;
                    case "and":
                    case 1:
                        $('<select class="js-relation" style="display: none"><option value="and" selected>并且</option><select/>').appendTo($condition);
                        break;
                    case "or":
                    case 0:
                        $('<select class="js-relation" style="display: none"><option value="or" selected>或者</option><select/>').appendTo($condition);
                        break;
                    default:
                        $('<select class="js-relation" style="display: none"><option value="and" selected>并且</option><select/>').appendTo($condition);
                        break;
                }
                conditionEl.append($condition);
                me.Component.find(".js-querybtns").show();
            },
            /***
             * 创建操作符
             * @param dvalue 默认符号
             * @returns {jQuery|HTMLElement}
             */
            createOp:function(dvalue){
                var $select=$("<select class='op'></select>");
                var ops="<option value='='>等于</option>" +
                    "<option value='>='>大等于</option>" +
                    "<option value='<='>小等于</option>" +
                    "<option value='>'>大于</option>" +
                    "<option value='<'>小于</option>" +
                    "<option value='like'>类似</option>" +
                    "<option value='in'>包括</option>" +
                    "<option value='between'>区间</option>" +
                    "<option value='<>'>不等于</option>";
                $select.append(ops);
                $select.val(dvalue);
                return $select;
            },
            fetchTemplate:function(index){
                var me=this;
                if(index==undefined||index==null||Ladder.getType(index)=="Number"){
                    var conditionel=null;
                    if(index==undefined||index==null)conditionel=me.conditionEl;
                    else {
                        var count=me.templateEl.find(".queryform").length;
                        if(index<0)index=me.templateEl.find(".queryform").length+index;
                        if(index<0||index>count)return [];
                        conditionel=me.templateEl.find(".queryform:eq("+index+")");
                    }
                    var template=[];
                    conditionel.find(".queryitem").each(function(){
                        var $this=$(this);
                        var queryitem={
                            fieldname:$this.attr("data-fieldname"),
                            op:$this.find(".op").val(),
                            relation:$this.find(".js-relation").val(),
                            val1:$this.find(".js-yui:eq(0)").attr("data-value")||$this.find(".js-yui:eq(0)").val(),
                            val2:$this.find(".js-yui:eq(1)").attr("data-value")||$this.find(".js-yui:eq(1)").val()
                        }
                        template.push(queryitem);
                    });
                    return {
                        template:template,
                        title:conditionel.attr("data-title"),
                        id:conditionel.attr("data-id"),
                        action:conditionel.attr("data-action")
                    };
                }
                if(index=="all"){
                    var total=[];
                    var count=this.templateEl.find(".queryform").length;
                    for (var i = 0; i < count; i++) total.push(me.fetchTemplate(i));
                    return total;
                }
            },
            loadTemplate:function(data){
                var me=this;
                if(data){
                    me.addTab(data);
                }
                else{
                    if(me.settings.id&&/local/.test(me.settings.store)){
                        var templateData=Ladder.getStore("QueryTemplate_"+me.settings.id);
                        if(templateData)
                            me.addTab(templateData);
                    }
                }
            },
            fetchCondition:function(index){
                var me=this;
                var conditions=me.fetchTemplate(index);
                switch (me.settings.take.toLocaleLowerCase()){
                    case "array":
                        return conditions.template;
                    case "sql":
                        var sql="";
                        conditions.template.forEach(function(item){
                            if(item.op=="between"){
                                if(item.val1)sql+=item.fieldname+">='"+item.val1+"' "+item.relation+" ";
                                if(item.val2)sql+=item.fieldname+"<='"+item.val2+"' "+item.relation+" "
                            }else{
                                if(item.val1)sql+=item.fieldname+item.op+"'"+item.val1+"' "+item.relation+" ";
                            }
                        });
                        return sql.replace(/\s*(and)*(or)*\s*$/,"");
                    case "object":
                    case "json":
                        var cnd={};
                        conditions.template.forEach(function(item){
                            if(item.op=="between"){
                                if(item.val1)cnd[item.fieldname+":>=:"+item.relation]=item.val1;
                                if(item.val2)cnd[item.fieldname+":<=:"+item.relation]=item.val2;
                            }else{
                                if(item.val1)cnd[item.fieldname+":"+item.op+":"+item.relation]=item.val1;
                            }
                        });
                        return cnd;
                }
            },
            /***
             *
             * @param index
             * @param isdelete
             */
            saveTemplate:function(index,isdelete){
                var me=this;
                var template=null;
                if(index==undefined||index==null)template=me.fetchTemplate();
                var type=Ladder.getType(index);
                if(type=="Number")template =me.fetchTemplate(index);
                if(type=="Object")template=index;
                if(!template)return;
                if(isdelete)template.action=-1;
                if(me.settings.onSave){
                    var ret=me.settings.onSave(template);
                    if(ret!=undefined&&!ret)return;
                }
                if(/local/.test(me.settings.store)){
                    var oldlist=Ladder.getStore("QueryTemplate_"+me.settings.id);
                    if(!oldlist||oldlist.length<1)oldlist=[];
                    if(!isdelete){
                        var ishandle=false;
                        for(var i=oldlist.length-1;i>=0;i--){
                            if(oldlist[i].id==template.id){
                                oldlist[i].template=template.template;
                                oldlist[i].title=template.title;
                                ishandle=true;
                                break;
                            }
                        }
                        if(!ishandle)oldlist.push(template);
                    }else{
                        oldlist = oldlist.filter(function(item){
                            return item.id!=template.id;
                        })
                    }
                    Ladder.setStore("QueryTemplate_"+me.settings.id,oldlist);
                }
                if(/server/.test(me.settings.store)){

                }
                me.Component.find(".tpls li[data-id="+template.id+"]").removeClass("nosave");

            },

            setHoldData:function(data){
                this.holdData=Ladder.clone(data);




            }

        }
    };
    if(typeof define === "function" && define.amd){
        require.config({
            // shim:{
            //   'yui':['form']
            // },
            paths: {
                "yui":'ladder-ui',
                'form': 'ladder-form'
            }
        });
        define(['form',"yui"],__functionForPlugin);
    }else{
        __functionForPlugin();
    }
})();

